package de.tabuma.shopping.logik;

import java.util.*;
import de.tabuma.shopping.entity.*;

/**
 * @author $Author: alefen $
 * @version $Revision: 1.1 $
 * @since $Date: 2009/07/21 19:37:33 $
 */
public class LicenseAssignmentFacade {

    public static int create(LicenseAssignment licenseAssignment, String user) {
        return (int) PMF.doCreate(licenseAssignment, user);
    }

    public static void update(LicenseAssignment licenseAssignment, String user) {
        PMF.doUpdate(licenseAssignment, user);
    }

    public static void remove(LicenseAssignment licenseAssignment, String user) {
        PMF.doRemove(licenseAssignment, user);
    }

    public static LicenseAssignment get(int id) {
        return PMF.get(id, new LicenseAssignment());
    }

    public static List<LicenseAssignment> getList(int key, int licenseType) {
        String keys[] = {"assignmentId", "licenseType"};
        String values[] = {""+key, ""+licenseType};
        return PMF.get(keys, values, new LicenseAssignment());
    }

    public static List<LicenseAssignment> getList(int licenseType) {
        String keys[] = {"licenseType"};
        String values[] = {""+licenseType};
        return PMF.get(keys, values, new LicenseAssignment());
    }

    public static List<LicenseAssignment> getListFromOrderLicensePackageRelationId(int olprId) {
        String keys[] = {"orderLicensePackageRelationId"};
        String values[] = {""+olprId};
        return PMF.get(keys, values, new LicenseAssignment());
    }

    public static int getCountAssignedLicenses(int licenseType) {
        List<LicenseAssignment> laList = getList(licenseType);
        int count = 0;
        for(int i=0;i<laList.size();i++) {
            count += laList.get(i).getLicenseCount();
        }
        return count;
    }

    public static int getCountUsedLicenses(int licenseType) {
        List<LicenseAssignment> laList = getList(licenseType);
        int count = 0;
        for(int i=0;i<laList.size();i++) {
            count += laList.get(i).getLicenseUsed();
        }
        return count;
    }

    public static int getUnusedLicenseForOrderedLicense(int olprId, int nr, LicensePackageFacade licensePackageFacade) {
        List<LicenseAssignment> laList = getListFromOrderLicensePackageRelationId(olprId);
        int assignedLicense = 0;
        for(int i=0;i<laList.size();i++) {
            assignedLicense += laList.get(i).getLicenseCount();
        }        
        OrderLicensePackageRelation olpr = OrderLicensePackageRelationFacade.get(olprId);
        LicensePackage licensePackage = licensePackageFacade.getLicensePackageWithID(olpr.getLicensePackageId());
        License license = licensePackage.getList()[nr];
        return license.getCount() - assignedLicense;
    }
    
}